package core;
BEGIN{push(@INC,".")};
use dispatch;
use IO::Socket::INET;
sub new {
    my ($self, $ip, $port) = @_;
    $obj = { "ip" => $ip, "port" => $port };
    bless($obj, $self);
    return $obj;
}
sub dispatcher_reg {
    my $self = shift;;

    my $funcname = shift;
    my $funref = shift;
    dispatch::reg($dispatch::ds,$funcname,$funref);
}

sub start_server {
    my ($self) = @_;
    my $server_port = $$self{"port"};
    my $ip = $$self{"ip"};

    $server = IO::Socket::INET->new(
        PeerAddr => $ip,
        LocalPort => $server_port,
        Type    => SOCK_STREAM,
        Reuse   => 1,
        Listen   => 10)   # 或者 SOMAXCONN
        or die "Couldn't be a tcp server on port $server_port: $!\n";

    while ($client = $server->accept()) {
        # $client 是新联接
        handle($client);
        print("close a client\n----------\n");
    }

    close($server);
}
sub handle {
    print("start handle\n--------------\n");
    my $client = shift;
    my @text_arr;
    my $action;
    my $funcname = <$client>;
    $funcname=~s/^\s*//;
    $funcname=~s/\s*$//;
    while(1) {
        my $text = <$client>;
        # print($text);
        last if ($text eq "\r\n");
        # last if ($text eq "");
        # $text=~s/^\s*//;
        # $text=~s/\s*$//;
        push(@text_arr,$text);
    }
    # print("--------------\n");
    # chomp ($text_arr[-1]);
    # my $funcname = shift(@text_arr);
    print("\$funcname is $funcname\n");
    if ($funcname eq "DESTROY") {
        close($client);
        return;
    }
    @result = $dispatch::ds->call_func($funcname,@text_arr);
    # print("\@result is "."@result\n");
    print $client @result;
    close($client);
}
sub DESTORY {
    my ($self) = @_;

}
1;